package com.xingkeduo.business.order.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xingkeduo.dto.*;
import com.xingkeduo.dto.param.*;
import com.xingkeduo.dto.transter.Comment;
import com.xingkeduo.dto.transter.Content;
import com.xingkeduo.dto.transter.JudgementList;
import com.xingkeduo.dto.transter.appointment.AppointmentParamDto;
import com.xingkeduo.dto.transter.appointment.AppointmentSubmit;
import com.xingkeduo.dto.transter.appointment.OrderAppointmentDto;
import com.xingkeduo.dto.transter.comment.CommentSubmit;
import com.xingkeduo.dto.transter.comment.ContentComment;
import com.xingkeduo.dto.transter.commentfinish.CommentFinishParameterDto;
import com.xingkeduo.dto.transter.commentfinish.Commentfinish;
import com.xingkeduo.dto.transter.commentfinish.ContentCommentFinsh;
import com.xingkeduo.dto.transter.evaluation.Contents;
import com.xingkeduo.dto.transter.evaluation.JsonRootBean;
import com.xingkeduo.dto.transter.evaluation.Store;
import com.xingkeduo.dto.transter.hairstyle.CommentHairStyle;
import com.xingkeduo.dto.transter.hairstyle.OrderHairDto;
import com.xingkeduo.dto.transter.order.*;
import com.xingkeduo.dto.transter.orderadd.OrderAdd;
import com.xingkeduo.dto.transter.orderdetail.ContentOrderDetail;
import com.xingkeduo.dto.transter.orderdetail.Hairstyle_list;
import com.xingkeduo.dto.transter.orderdetail.OrderDetail;
import com.xingkeduo.dto.transter.orderdetail.Selected_hair;
import com.xingkeduo.dto.transter.orderserviec.OrderServiceType;
import com.xingkeduo.dto.transter.orderserviec.ServiceStatic;
import com.xingkeduo.dto.transter.paydetail.*;
import com.xingkeduo.dto.transter.refund.Refund;
import com.xingkeduo.dto.transter.refunddetail.ContentRefundDetail;
import com.xingkeduo.dto.transter.refunddetail.RefundDetail;
import com.xingkeduo.dto.transter.shop.ShopsDTO;
import com.xingkeduo.dto.transter.shop.StoreRemoteDto;
import com.xingkeduo.dto.transter.upload.CertifyResult;
import com.xingkeduo.dto.transter.upload.ImgResult;
import com.xingkeduo.dto.transter.upload.ImgUpload;
import com.xingkeduo.dto.transter.verification.ContentVerification;
import com.xingkeduo.dto.transter.verification.VerificationCode;
import com.xingkeduo.pojo.enums.CommentFinish;
import com.xingkeduo.pojo.enums.OrderStatus;
import com.xingkeduo.remote.*;
import com.xingkeduo.remote.feign.*;
import com.xingkeduo.utils.DateTimeUtils;
import com.xingkeduo.utils.PageResponseDTO;
import com.xingkeduo.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


@Service
@Slf4j
public class CommentsService {

    @Resource
    private CommentsFeignService commentsFeignService;

    @Resource
    private CommentRemoteService commentRemoteService;

    @Resource
    private AdminRemoteService adminRemoteService;

    @Resource
    private StoreRemoteService storeRemoteService;

    @Resource
    private OrderRemoteService orderRemoteService;

    @Resource
    private OrderFeignService orderFeignService;

    @Resource
    QuestionnaireRemoteService questionnaireRemoteService;

    @Resource
    private OssFeignService ossFeignService;

    @Resource
    private WordPadRemoteService wordPadRemoteService;

    @Resource
    private MarketingRemoteService marketingRemoteService;

    @Resource
    private MarketingFeignService marketingFeignService;

    @Resource
    private AdminFeignService adminFeignService;

    private static final String errorUserAuthMsg = "用户信息更新中 请等待";

    public Comment getCommensByUserId(CommentList commentList) {
        String labels = labelsCovert(commentList);
        int num = (commentList.getOffset() + 6) / 6;

        ResponseUtils<PageResponseDTO<QueryByUserIdResponseDto>> responseDtoResponseUtils = commentsFeignService.getCommensByUserId(commentList.getF_user_id(), num, 6, labels, commentList.getIs_user(), commentList.getF_store_id());
        if (responseDtoResponseUtils.success()) {
            PageResponseDTO<QueryByUserIdResponseDto> pageResponseDTO = responseDtoResponseUtils.getData();
            Comment comment = new Comment();
            Content content = new Content();
            List<JudgementList> judgementList = pageResponseDTO.getDtoLists().stream()
                    .map(this::queryUserCovertToDto)
                    .collect(Collectors.toList());
            content.covert(judgementList, pageResponseDTO, commentRemoteService.queryLabelsByStart());
            comment.covert(content, responseDtoResponseUtils);
            return comment;
        }
        return null;
    }

    private String labelsCovert(CommentList commentList) {
        if (!"all".equals(commentList.getLabelall())) {
            StringBuffer sb = new StringBuffer();
            labelsDispose(sb, String.valueOf(commentList.getLabel4()), commentRemoteService.getLabelIds(4));
            labelsDispose(sb, String.valueOf(commentList.getLabel5()), commentRemoteService.getLabelIds(5));
            if (sb.lastIndexOf(",") > 0) {
                sb.deleteCharAt(sb.length() - 1);
            }
            return sb.toString();
        }
        return "";
    }


    public void labelsDispose(StringBuffer sb, String label, Map<String, Long> map) {
        List<String> labelList = Arrays.asList(label.split(","));
        for (String str : labelList) {
            if (map.containsKey(str)) {
                sb.append(map.get(str)).append(",");
            }
        }
    }

    public JudgementList queryUserCovertToDto(QueryByUserIdResponseDto queryByUserIdResponseDto) {
        if (queryByUserIdResponseDto == null) {
            return null;
        }
        JudgementList judgementList = new JudgementList();
        judgementList.covert(queryByUserIdResponseDto);
        return judgementList;
    }

    /**
     * 获取评价等级
     *
     * @param commentCreateDto
     * @return
     */
    public JsonRootBean getCommensLabels(CommentCreateDto commentCreateDto) {
        JsonRootBean jsonRootBean = new JsonRootBean();
        StoreRemoteDto byStoreId = storeRemoteService.getByStoreId(Integer.valueOf(commentCreateDto.getStore_id()));
        Map<String, Object> objects = commentRemoteService.getLabes();
        String adminId = orderRemoteService.getAdminId(commentCreateDto.getOrder_no());
        Map<String, String> map = adminRemoteService.queryAdminInfo(adminId);
        Store store = new Store();
        store.covert(byStoreId);
        Contents content = new Contents();
        content.covert(store, map, objects);
        jsonRootBean.covert(content);
        return jsonRootBean;
    }

    /**
     * 获取验证码
     *
     * @param refreshCodeDto
     * @return
     */
    public VerificationCode getRefreshCodeDto(RefreshCodeDto refreshCodeDto) {
        VerificationCode verificationCode = new VerificationCode();
        ContentVerification content = new ContentVerification();
        ResponseUtils<RefreshCodeResponseDto> responseUtils = orderFeignService.obtainCode(refreshCodeDto.getOrder_no());
        content.covert(responseUtils);
        verificationCode.covert(responseUtils, content);
        return verificationCode;
    }

    /**
     * 获取订单列表
     *
     * @param orderParameterDto
     * @return
     */
    public OrderResponseDto userQuery(OrderParameterDto orderParameterDto) {
        OrderResponseDto orderResponseDto = new OrderResponseDto();
        //先校验user_id是否传值  没传值则返回9004
        if (StringUtils.isBlank(orderParameterDto.getF_user_id())) {
            orderResponseDto.errorUserAuth(errorUserAuthMsg);
            return orderResponseDto;
        }
        long f_user_id = Long.parseLong(orderParameterDto.getF_user_id());
        //再校验user_id对应的用户是否存在  不存在则返回9004
        if (f_user_id > 0L) {//调用子峰接口 进行判断
            ResponseUtils<Long> responseUtils = adminFeignService.checkUserExist(f_user_id,orderParameterDto.getMobile_type());
            if (!responseUtils.success()) {
                orderResponseDto.errorUserAuth(errorUserAuthMsg);
                return orderResponseDto;
            }
        }
        orderParameterDto.covert(orderParameterDto);

        ContentOrder contentOrder = new ContentOrder();
        int num = (orderParameterDto.getOffset() + 5) / 5;
        ResponseUtils<PageResponseDTO<OrderUserResponseDto>> responseUtils = orderFeignService.userQuery(orderParameterDto.getF_user_id(), orderParameterDto.getStatus(), num, 5);
        if (responseUtils.success()) {
            PageResponseDTO<OrderUserResponseDto> orderUserResponseDtos = responseUtils.getData();
            List<Order_list> order_lists = orderUserResponseDtos.getDtoLists().stream()
                    .map((OrderUserResponseDto orderUserResponseDto) -> queryOrders(orderUserResponseDto, orderParameterDto)).filter(Objects::nonNull)
                    .collect(Collectors.toList());
            order_lists.forEach(Order_list -> Order_list.setImg_url(orderRemoteService.getAdminImg(Order_list.getOrder_no())));

            //查询用户未支付订单
            UnpaidOrderRecord unpaidOrderRecord = orderRemoteService.getUnpaidOrderRecord(String.valueOf(orderParameterDto.getF_user_id()));
            contentOrder.covert(order_lists, responseUtils.getData(), unpaidOrderRecord);
        }
        orderResponseDto.covert(responseUtils, contentOrder);
        return orderResponseDto;
    }

    /**
     * c
     *
     * @param orderUserResponseDto
     * @return
     */
    private Order_list queryOrders(OrderUserResponseDto orderUserResponseDto, OrderParameterDto orderParameterDto) {
        if (orderUserResponseDto == null) {
            return null;
        }
        if (OrderStatus.NOT_PAY == orderUserResponseDto.getStatus()) {
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime localDateTime = orderUserResponseDto.getCreatedTime().plusSeconds(60);
            if (now.isAfter(localDateTime)) {
                return null;
            }
        }
        boolean can_buy = false;
        Order_list order_list = new Order_list();
        Queue queue = new Queue();
        queue.covert(orderUserResponseDto);
        order_list.covert(orderUserResponseDto, queue, can_buy, orderParameterDto);
        return order_list;
    }

    /**
     * 剪发订单详情
     *
     * @param orderDetailParameterDto
     * @return
     */
    public OrderDetail userQueryDetail(OrderDetailParameterDto orderDetailParameterDto) {
        OrderDetail orderDetail = new OrderDetail();
        ResponseUtils<OrderDetailResponseDto> orderDetailResponseDto = orderRemoteService.queryByOrderNO(orderDetailParameterDto.getOrder_no());
        OrderDetailResponseDto data = orderDetailResponseDto.getData();
        if (data != null) {
            if (OrderStatus.REFUND_DONE.equals(data.getStatus())) {
                orderDetail.setError(3);
                orderDetail.setReason("此订单已退款！");
                return orderDetail;
            }

        }

        ShopsDTO shopsDTO = storeRemoteService.queryStoreById(orderDetailParameterDto.getStore_id());
        ContentOrderDetail contentOrderDetail = new ContentOrderDetail();

        List<Hairstyle_list> hairstyle_lists = storeRemoteService.queryHairStyle();
        Selected_hair selected_hair = storeRemoteService.hairstyle(data.getHairId());
        ShopsDaysTable shopsDaysTable = storeRemoteService.doGetShopServprodDetail(data.getStoreId());
        data.setServiceTypeName("");
        if (StringUtils.isNotEmpty(data.getServiceTypeId())) {
            data.setServiceTypeName(storeRemoteService.getServprod(data.getServiceTypeId()));
        }
        Object wait_num = wordPadRemoteService.getLineNum(DateTimeUtils.yyyy_MM_dd_HH_mm_ss(data.getAppointmentStartTime()), data.getAppointmentAdminId(), data.getStoreId());
        log.info("剪发订单详情userQueryDetail:{}", JSON.toJSONString(data));
        contentOrderDetail.covert(shopsDTO, data, hairstyle_lists, selected_hair, shopsDaysTable, wait_num);

        orderDetail.covert(contentOrderDetail, orderDetailResponseDto);
        return orderDetail;
    }

    /**
     * 更改发型
     *
     * @param hairStyleParameterDto
     * @return
     */
    public CommentHairStyle hair(HairStyleParameterDto hairStyleParameterDto) {
        CommentHairStyle commentHairStyle = new CommentHairStyle();
        OrderHairDto orderHairDto = new OrderHairDto();
        orderHairDto.covert(hairStyleParameterDto);
        ResponseUtils hair = orderFeignService.hair(orderHairDto);
        commentHairStyle.covert(hair);
        return commentHairStyle;
    }

    /**
     * 退款订单详情
     *
     * @param refundDetailParameterDto
     * @return
     */
    public RefundDetail refundDetail(RefundDetailParameterDto refundDetailParameterDto) {
        //查询订单详情和店铺详情补全小程序数据
        ResponseUtils<OrderDetailResponseDto> orderDetailResponseDto = orderRemoteService.queryByOrderNO(refundDetailParameterDto.getOrder_no());
        ShopsDTO shopsDTO = storeRemoteService.queryStoreById(Integer.valueOf(refundDetailParameterDto.getStore_id()));
        OrderDetailResponseDto data = orderDetailResponseDto.getData();
        String appointment_admin_avatar = adminRemoteService.getAdminImg(data.getAppointmentAdminId());
        ContentRefundDetail contentRefundDetail = new ContentRefundDetail();
        contentRefundDetail.covert(data, shopsDTO, appointment_admin_avatar);
        RefundDetail refundDetail = new RefundDetail();
        refundDetail.covert(contentRefundDetail, orderDetailResponseDto);
        return refundDetail;

    }

    /**
     * 下单详情
     *
     * @param payDetailParameterDto
     * @return
     */
    public PayDetail payDetail(PayDetailParameterDto payDetailParameterDto) {
        ResponseUtils<OrderDetailResponseDto> orderDetailResponseDto = orderRemoteService.queryByOrderNO(payDetailParameterDto.getOrder_no());
        ShopsDTO shopsDTO = storeRemoteService.queryStoreById(orderRemoteService.queryStoreId(orderDetailResponseDto));
        OrderDetailResponseDto data = orderDetailResponseDto.getData();

        if (data != null) {
            data.setAdminAvatar(adminRemoteService.getAdminImg(data.getAdminId()));
        }


        StorePayDetail storePayDetail = new StorePayDetail();
        ShopsDaysTable shopsDaysTable = storeRemoteService.doGetShopServprodDetail(String.valueOf(shopsDTO.getId()));
        storePayDetail.covert(shopsDTO, shopsDaysTable);

        ActivityDto activityDto = null;
        String activityName = "";
        if (data.getActivityType() != null) {
            activityDto = JSON.parseObject(data.getActivityDetail(), ActivityDto.class);
            if (activityDto != null) {
                activityName = activityDto.getActivityName();
            }

        }
        MarketDto marketDto = null;
        if (data.getMarketingType() != null) {
            marketDto = JSON.parseObject(data.getCardCouponDetail(), MarketDto.class);
        }
        Coupon coupon = new Coupon();
        coupon.covert(data.getMarketingType(), marketDto);
        Card card = new Card();
        card.covert(data.getMarketingType(), marketDto);

        Activity activity = new Activity();
        activity.covert(data.getActivityType(), activityDto);

        ContentPayDetail contentPayDetail = new ContentPayDetail();
        MarketActivityDto marketActivityInfo = marketingRemoteService.getMarketActivityInfo(data);
        contentPayDetail.covert(data, storePayDetail, coupon, card, activityName, activity, marketActivityInfo);

        PayDetail payDetail = new PayDetail();
        payDetail.covert(contentPayDetail, orderDetailResponseDto);

        return payDetail;
    }

    /**
     * 添加创建订单
     *
     * @param orderAddParameterDto
     * @return
     */
    public OrderAdd orderAdd(OrderAddParameterDto orderAddParameterDto) {
        OrderAdd orderAdd = new OrderAdd();
        OrderInitDto orderInitDto = new OrderInitDto();
        String adminName = adminRemoteService.getAdminName(orderAddParameterDto.getAdmin_id());
        Map<String, Object> map = null;

        try {
            if (orderAddParameterDto.getService_type() == 4) {
                map = wordPadRemoteService.getStockIdByStaffIdAndBaberStoreId(Long.valueOf(orderAddParameterDto.getAdmin_id()), Long.valueOf(orderAddParameterDto.getStore_id()), orderAddParameterDto.getAppointment_time(), orderAddParameterDto.getAppointment_date());
            } else {
                map = wordPadRemoteService.getStockIdByStaffIdAndStoreId(Long.valueOf(orderAddParameterDto.getAdmin_id()), Long.valueOf(orderAddParameterDto.getStore_id()), orderAddParameterDto.getAppointment_time(), orderAddParameterDto.getAppointment_date());
            }
        } catch (Exception e) {
            orderAdd.setError(504);
            orderAdd.setReason("当前时间不可约,请选择其他时间!");
            return orderAdd;
        }


        if (map == null) {
            orderAdd.setError(1);
            orderAdd.setReason("该时间段库存信息为空！");
            return orderAdd;
        }

        if (bfTime(String.valueOf(map.get("startTime")))) {
            orderAdd.setError(1);
            orderAdd.setReason("预约时间已过！");
            return orderAdd;
        }


        orderInitDto.covert(orderAddParameterDto, adminName, map);
        log.info("创建订单 order_add:{}", JSON.toJSONString(orderInitDto));
        ResponseUtils insert = orderFeignService.insert(orderInitDto);

        orderAdd.covert(insert);
        return orderAdd;

    }

    /**
     * @return boolean true已过，false未过
     * @description: 判断预约时间是否已过
     * @author: ch
     * @Param [startTime]
     * @date: 2019-06-17 15:11
     **/
    public boolean bfTime(String startTime) {
        LocalDateTime nowTime = LocalDateTime.now();
        LocalDateTime endTime = DateTimeUtils.yyyy_MM_dd_HH_mm_ss(startTime);
        return nowTime.isAfter(endTime);
    }

    /**
     * 添加评论
     *
     * @param commentSubmitParameterDto
     * @return
     */
    public CommentSubmit commentSubmit(CommentSubmitParameterDto commentSubmitParameterDto) {
        CommentSubmit comments = commentRemoteService.queryDetailByorderId(commentSubmitParameterDto.getOrder_no());
        if (comments != null) {
            return comments;
        }
        CommentSubmit orderComment = orderRemoteService.queryOrder(commentSubmitParameterDto.getOrder_no());
        if (orderComment != null) {
            return orderComment;
        }
        String labels = getlabelsCovert(commentSubmitParameterDto);
        CommentInitDto commentInitDto = new CommentInitDto();
        commentInitDto.covert(commentSubmitParameterDto, labels);
        ResponseUtils responseUtils = commentsFeignService.insertNO(commentInitDto);

        ContentComment contentComment = new ContentComment();
        contentComment.covert();

        CommentSubmit commentSubmit = new CommentSubmit();
        commentSubmit.covert(responseUtils, contentComment);
        return commentSubmit;
    }


    private String getlabelsCovert(CommentSubmitParameterDto commentSubmitParameterDto) {
        if (StringUtils.isNotEmpty(commentSubmitParameterDto.getTag_selected())) {
            StringBuffer sb = new StringBuffer();
            labelsDispose(sb, commentSubmitParameterDto.getTag_selected(), commentRemoteService.getLabelIds(commentSubmitParameterDto.getStar()));
            if (sb.lastIndexOf(",") > 0) {
                sb.deleteCharAt(sb.length() - 1);
            }
            return sb.toString();
        }
        return "";
    }


    /**
     * 订单退款
     *
     * @param orderRefundDto
     * @return
     */
    public Refund refund(OrderRefundDto orderRefundDto) {
        Refund refund = new Refund();
        OrderRefundParamDto orderRefundParamDto = new OrderRefundParamDto();
        if (StringUtils.isEmpty(orderRefundDto.getReason())) {
            refund.setError(1);
            refund.setReason("请选择退款理由");
            return refund;
        }

        ResponseUtils<OrderDetailResponseDto> responseDtoResponseUtils = orderFeignService.queryByOrderNO(orderRefundDto.getOrder_no());
        if (!responseDtoResponseUtils.success()) {
            refund.setError(1);
            refund.setReason("订单不存在");
            return refund;
        }
        OrderDetailResponseDto data = responseDtoResponseUtils.getData();

        if (data.getServiceDown()) {
            refund.setError(1);
            refund.setReason("你的订单已经完成服务，请返回。");
            return refund;
        }
        if ("8".equals(String.valueOf(data.getStatus().getKey()))) {
            refund.setError(1);
            refund.setReason("你的订单正在服务中！请耐心等待");
            return refund;
        }

        String id = data.getId() + "";
        orderRefundParamDto.covert(orderRefundDto, id);
        ResponseUtils responseUtils = orderFeignService.userRefund(orderRefundParamDto);

        refund.covert(responseUtils);
        return refund;
    }

    /**
     * 修改预约时间
     *
     * @param appointmentParamDto
     * @return
     */
    public AppointmentSubmit changeAppointment(AppointmentParamDto appointmentParamDto) {

        AppointmentSubmit appointmentSubmit = new AppointmentSubmit();
        Boolean notPayOrderNo = orderRemoteService.getNotPayOrderNo(appointmentParamDto.getF_user_id());
        if (notPayOrderNo) {
            appointmentSubmit.setReason("您有未完成服务的订单，请完成后预约");
            appointmentSubmit.setError(1001);
            appointmentSubmit.setContent("");
            return appointmentSubmit;
        }

        //判断是否是修改活动信息
        if (StringUtils.isNotEmpty(appointmentParamDto.getActivity_id())) {
            ResponseUtils responseUtils = orderFeignService.changeMarket(appointmentParamDto.getOrder_no(), appointmentParamDto.getActivity_id(), "0");
            appointmentSubmit.covert(responseUtils);
            return appointmentSubmit;
        }


        if (StringUtils.isNotEmpty(appointmentParamDto.getCoupon_id()) && StringUtils.isNotEmpty(appointmentParamDto.getCard_id())) {
            if ("0".equals(appointmentParamDto.getCoupon_id()) && "0".equals(appointmentParamDto.getCard_id())) {
                ResponseUtils responseUtils = orderFeignService.changeMarket(appointmentParamDto.getOrder_no(), appointmentParamDto.getCoupon_id(), "1");
                appointmentSubmit.covert(responseUtils);
                return appointmentSubmit;
            } else {
                //判断是否修改优惠券信息
                if (!"0".equals(appointmentParamDto.getCoupon_id())) {
                    ResponseUtils responseUtils = orderFeignService.changeMarket(appointmentParamDto.getOrder_no(), appointmentParamDto.getCoupon_id(), "1");
                    appointmentSubmit.covert(responseUtils);
                }

                //判断是否修改卡券信息
                if (!"0".equals(appointmentParamDto.getCard_id())) {
                    ResponseUtils responseUtils = orderFeignService.changeMarket(appointmentParamDto.getOrder_no(), appointmentParamDto.getCard_id(), "2");
                    appointmentSubmit.covert(responseUtils);
                }
                return appointmentSubmit;
            }
        }


        //修改预约时间
        return changeTime(appointmentSubmit, appointmentParamDto);

    }


    /**
     * 修改预约时间
     *
     * @param appointmentSubmit
     * @param appointmentParamDto
     * @return
     */
    public AppointmentSubmit changeTime(AppointmentSubmit appointmentSubmit, AppointmentParamDto appointmentParamDto) {
        OrderAppointmentDto orderAppointmentDto = new OrderAppointmentDto();
        ResponseUtils<OrderDetailResponseDto> orderDetailResponseDto = orderRemoteService.queryByOrderNO(appointmentParamDto.getOrder_no());
        OrderDetailResponseDto orderDetailResponseDto1 = orderDetailResponseDto.getData();
        Map<String, Object> map = null;
        if ("4".equals(orderDetailResponseDto1.getServiceTypeId())) {
            map = wordPadRemoteService.getStockIdByStaffIdAndBaberStoreId(Long.valueOf(appointmentParamDto.getAdmin_id()), Long.valueOf(orderRemoteService.queryStoreId(orderDetailResponseDto)), appointmentParamDto.getAppointment_time(), appointmentParamDto.getAppointment_date());

        } else {
            map = wordPadRemoteService.getStockIdByStaffIdAndStoreId(Long.valueOf(appointmentParamDto.getAdmin_id()), Long.valueOf(orderRemoteService.queryStoreId(orderDetailResponseDto)), appointmentParamDto.getAppointment_time(), appointmentParamDto.getAppointment_date());
        }

        if (map == null) {
            appointmentSubmit.setReason("预约库存不存在！");
            appointmentSubmit.setError(1);
            appointmentSubmit.setContent("");
            return appointmentSubmit;
        }
        orderAppointmentDto.covert(appointmentParamDto, map);
        ResponseUtils appointment = orderFeignService.appointment(orderAppointmentDto);
        appointmentSubmit.covert(appointment);
        return appointmentSubmit;
    }


    /**
     * 修改预约时间(支付后)
     *
     * @param appointmentParamDto
     * @return
     */
    public AppointmentSubmit changeAppointmentTime(AppointmentParamDto appointmentParamDto) {

        AppointmentSubmit appointmentSubmit = new AppointmentSubmit();
        Boolean notPayOrderNo = orderRemoteService.getNotPayOrderNo(appointmentParamDto.getF_user_id());
        if (notPayOrderNo) {
            appointmentSubmit.setReason("您有未完成服务的订单，请完成后预约");
            appointmentSubmit.setError(1001);
            appointmentSubmit.setContent("");
            return appointmentSubmit;
        }

        OrderAppointmentDto orderAppointmentDto = new OrderAppointmentDto();
        ResponseUtils<OrderDetailResponseDto> orderDetailResponseDto = orderRemoteService.queryByOrderNO(appointmentParamDto.getOrder_no());
        OrderDetailResponseDto orderDetailResponseDto1 = orderDetailResponseDto.getData();
        Map<String, Object> map = null;
        if ("4".equals(orderDetailResponseDto1.getServiceTypeId())) {
            map = wordPadRemoteService.getStockIdByStaffIdAndBaberStoreId(Long.valueOf(appointmentParamDto.getAdmin_id()), Long.valueOf(orderRemoteService.queryStoreId(orderDetailResponseDto)), appointmentParamDto.getAppointment_time(), appointmentParamDto.getAppointment_date());

        } else {
            map = wordPadRemoteService.getStockIdByStaffIdAndStoreId(Long.valueOf(appointmentParamDto.getAdmin_id()), Long.valueOf(orderRemoteService.queryStoreId(orderDetailResponseDto)), appointmentParamDto.getAppointment_time(), appointmentParamDto.getAppointment_date());
        }
        if (map == null) {
            appointmentSubmit.setReason("预约库存不存在！");
            appointmentSubmit.setError(1);
            appointmentSubmit.setContent("");
            return appointmentSubmit;
        }
        orderAppointmentDto.covert(appointmentParamDto, map);
        if (orderDetailResponseDto.getData().getStatus().getKey() == 5) {
            ResponseUtils appointment = orderFeignService.reApply(orderAppointmentDto);
            appointmentSubmit.covert(appointment);
            return appointmentSubmit;
        }

        ResponseUtils<OrderDetailResponseDto> responseDtoResponseUtils = orderFeignService.queryByOrderNO(orderAppointmentDto.getOrderNo());
        OrderDetailResponseDto data = responseDtoResponseUtils.getData();

        if (!"1".equals(String.valueOf(data.getStatus().getKey()))) {
            String value = data.getStatus().getValue();
            appointmentSubmit.setError(1001);
            appointmentSubmit.setReason("订单" + value + "，无法修改预约时间");
            appointmentSubmit.setContent("订单" + value + "，无法修改预约时间");
            return appointmentSubmit;
        }
        ResponseUtils appointment = orderFeignService.appointmentCompleted(orderAppointmentDto);
        appointmentSubmit.covert(appointment);
        return appointmentSubmit;
    }

    /**
     * 评价完成
     *
     * @param commentFinishParameterDto
     * @return
     */
    public Commentfinish commentFinish(CommentFinishParameterDto commentFinishParameterDto) {
        Commentfinish commentfinish = new Commentfinish();

        if (orderRemoteService.orderStatus(commentFinishParameterDto)) {
            commentfinish.covert(CommentFinish.ORDER);
        } else if (questionnaireRemoteService.questionCommitBF(commentFinishParameterDto)) {
            commentfinish.covert(CommentFinish.QUESTION);
        } else {
            ContentCommentFinsh contentCommentFinsh = new ContentCommentFinsh();
//            Todo
            contentCommentFinsh.covert(queryShopsDTO(commentFinishParameterDto.getOrder_no()));
            commentfinish.fill(contentCommentFinsh);
        }
        return commentfinish;
    }


    /**
     * 根据订单orderNo 获取店铺信息
     *
     * @param orderNo
     * @return
     */
    public ShopsDTO queryShopsDTO(String orderNo) {
        ResponseUtils<OrderDetailResponseDto> orderDetailResponseDto = orderRemoteService.queryByOrderNO(orderNo);
        return storeRemoteService.queryStoreById(orderRemoteService.queryStoreId(orderDetailResponseDto));
    }

    /**
     * 图片上传
     *
     * @param file
     * @return
     */
    public ImgResult uploadComment(MultipartFile file) {
        String result = ossFeignService.uploadComment(file);
        JSONObject object = JSON.parseObject(result);
        ImgResult imgResult = new ImgResult();
        ImgUpload imgUpload = new ImgUpload();
        boolean status = (int) object.get("status") == 1;
        if (status) {
            JSONObject data = JSON.parseObject(String.valueOf(object.get("data")));
            String current = String.valueOf(data.get("current"));
            imgUpload.covert(current);
        }
        imgResult.covert(status, imgUpload);
        return imgResult;
    }


    /**
     * 图片上传
     *
     * @param file
     * @return
     */
    public CertifyResult certify(MultipartFile file) {
        String result = ossFeignService.uploadComment(file);
        JSONObject object = JSON.parseObject(result);
        CertifyResult certifyResult = new CertifyResult();
        boolean status = (int) object.get("status") == 1;
        String imgAddr = "";
        if (status) {
            JSONObject data = JSON.parseObject(String.valueOf(object.get("data")));
            imgAddr = String.valueOf(data.get("current"));

        }
        certifyResult.covert(status, imgAddr);
        return certifyResult;
    }


    /**
     * @param store_id
     * @param order_no
     * @return
     */
    public OrderServiceType getOrderService(String store_id, String order_no) {
        OrderServiceType orderServiceType = new OrderServiceType();
        try {
            ResponseUtils<OrderDetailResponseDto> orderDetailResponseDto = orderRemoteService.queryByOrderNO(order_no);
            ServiceStatic serviceStatic = new ServiceStatic();
            serviceStatic.covert(orderDetailResponseDto);
            orderServiceType.covert(orderDetailResponseDto, serviceStatic);
        } catch (Exception e) {
            orderServiceType.error();
        }

        return orderServiceType;
    }


    /**
    * @description: 判断用户有没有barber券
    * @author: ch
    * @Param [consumerPrivateParameterDto]
    * @return com.xingkeduo.dto.transter.upload.CertifyResult
    * @date: 2019-08-01 18:49
    **/
    public Boolean orderDetailModal(ConsumerPrivateParameterDto consumerPrivateParameterDto) {
        log.info("判断用户有没有barber券 consumerPrivateParameterDto:{}", JSON.toJSONString(consumerPrivateParameterDto));
        ResponseUtils<OrderDetailResponseDto> responseDtoResponseUtils = orderFeignService.queryByOrderNO(consumerPrivateParameterDto.getOrder_no());
        OrderDetailResponseDto data = responseDtoResponseUtils.getData();
        String serviceTypeId = data.getServiceTypeId();
        String stores="4,6,7";
        String[] split = stores.split(",");
        List<String> list = Arrays.asList(split);
        if(list.contains(serviceTypeId)){
            //TODO 根据用户id查询 有没有券 有返回true，没有返回false
            long f_user_id = consumerPrivateParameterDto.getF_user_id();

            ResponseUtils<Boolean>  responseUtils = marketingFeignService.checkUserHasBarberCoupon(f_user_id,serviceTypeId);
            log.info("活动返回值 responseUtils:{}", JSON.toJSONString(responseUtils));
            if(responseUtils.success()){
                if(responseUtils.getData()){
                    return true;
                }
            }
        }
        return false;
    }
}
